using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;

namespace ExcelRefresh.Excel
{
    /// <summary>
    /// Peridically scans one or more folders 
    /// </summary>
    public class FileScavenger : IDisposable
    {
        private Timer _tickTock;
        private readonly string[] _folders;
        private readonly IProducerConsumerCollection<FileToRefresh> _files;

        public FileScavenger(string[] folders, IProducerConsumerCollection<FileToRefresh> files)
        {
            _folders = folders;
            _files = files;
            CheckForFiles(null);
            
            var timeUntilTomorrow = DateTime.Today.AddDays(1).AddMinutes(1) - DateTime.Now;
            CheckForFiles(null);
            _tickTock = new Timer(CheckForFiles, null, timeUntilTomorrow, Settings.FileScanFrequency);
        }

        public void Dispose()
        {
            if (_tickTock == null) return;
            _tickTock.Dispose();
            _tickTock = null;
        }

        private void CheckForFiles(object state)
        {
            var newFiles = from folder in _folders
                           from file in Directory.EnumerateFiles(folder, "*.xlsx", SearchOption.AllDirectories)
                           let fileToRefresh = new FileToRefresh(file) { RootPath = folder }
                           where fileToRefresh.IsStale 
                           where !_files.Contains(fileToRefresh)
                           group fileToRefresh by file into fileNames
                           let fileToRefresh = fileNames.First()
                           orderby fileToRefresh.Priority descending
                           select fileToRefresh;

            foreach (var file in newFiles)
            {
                Trace.TraceInformation("Queueing {0}", file);
                _files.TryAdd(file);
            }
        }      
    }
}